package com.senlingspace.web.controller.weixin;

import com.alibaba.fastjson2.JSON;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.framework.security.context.SecurityUtilExt;
import com.senlingspace.system.domain.SlkjCustomerAddress;
import com.senlingspace.system.service.ISlkjCustomerAddressService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 小程序地址相关
 *
 * @author lebronjames
 * @date 2024/10/02
 */
@Slf4j
@Validated
@AllArgsConstructor
@RestController
@RequestMapping(path = "/wmp/address/v1")
public class MiniAppAddressController {

    private final ISlkjCustomerAddressService iSlkjCustomerAddressService;


    /**
     * 地址列表
     *
     * @return {@link AjaxResult }
     */
    @GetMapping(path = "/list")
    public AjaxResult addresses() {
        List<SlkjCustomerAddress> addresses = iSlkjCustomerAddressService.selectAllByCustomerId(SecurityUtilExt.getCustomerId());
        return AjaxResult.success(addresses);
    }

    /**
     * 默认地址
     *
     * @return {@link AjaxResult }
     */
    @GetMapping(path = "/default")
    public AjaxResult defaultAddress() {
        return AjaxResult.success(iSlkjCustomerAddressService.getDefault(SecurityUtilExt.getCustomerId()));
    }

    /**
     * 设置默认地址
     *
     * @param addressId
     * @return {@link AjaxResult }
     */
    @PutMapping(path = "/default/{addressId}")
    public AjaxResult setDefault(@PathVariable Long addressId) {
        log.info("设置默认地址，入参:{}", addressId);
        return iSlkjCustomerAddressService.setDefault(addressId, SecurityUtilExt.getCustomerId());
    }

    /**
     * 更新地址
     *
     * @param address
     * @return {@link AjaxResult }
     */
    @PutMapping(path = "/update")
    public AjaxResult update(@RequestBody SlkjCustomerAddress address) {
        log.info("更新地址，入参:{}", JSON.toJSONString(address));
        if (Objects.isNull(address.getAddressId())) {
            return AjaxResult.error("地址ID不能为空！");
        }
        return iSlkjCustomerAddressService.updateById(address);
    }

    /**
     * 保存地址
     *
     * @param address
     * @return {@link AjaxResult }
     */
    @PostMapping(path = "/save")
    public AjaxResult save(@RequestBody SlkjCustomerAddress address) {
        log.info("保存地址，入参:{}", JSON.toJSONString(address));
        address.setCustomerId(SecurityUtilExt.getCustomerId());
        return iSlkjCustomerAddressService.insert(address);
    }

    /**
     * 删除地址
     *
     * @param addressId
     * @return {@link AjaxResult }
     */
    @DeleteMapping(path = "/delete/{addressId}")
    public AjaxResult delete(@PathVariable Long addressId) {
        log.info("删除地址，入参:{}", addressId);
        return iSlkjCustomerAddressService.deleteById(addressId, SecurityUtilExt.getCustomerId());
    }

}
